package com.doit.demo.day02.sources;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Random;


/**
 * @DATE 2022/2/15/20:23
 * @Author MDK
 * @Version 2021.2.2
 *
 *
 * 自定义的Source(非并行)
 *  *
 *  *      仅仅实现了SourceFunction,那么该Source就是一个非并行的Source
 *  *      如果Source的run方法产生数据, [方法执行完后自行退出] ,该Source就是一个有限的数据流
 *
 *
 *
 **/
public class CustomSource2 {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",8881);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Integer> nums = env.addSource(new SourceFunction<Integer>() {
            boolean flag = true;
            @Override
            public void run(SourceContext<Integer> sourceContext) throws Exception {
                System.out.println("run method invoked ~~~~~");
                Random random = new Random();
                while (flag){
                    Thread.sleep(2000);
                    sourceContext.collect(random.nextInt(100));
                }
            }

            @Override
            public void cancel() {
                flag = false;
                System.out.println("cancel method invoked !!!!!");
            }
        });

        System.out.println("实现SourceFunction自定义的Source的并行度:" + nums.getParallelism());
        nums.print();
        env.execute();
    }
}
